package com.example.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AdminFilter implements Filter {

//    Filter 构造器与初始化 在web工程启动时执行
//           过滤方法      拦截请求时执行
//           销毁方法      停止web工程时执行


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter初始化");
        //    FilterConfig包含配置信息
        System.out.println("filter-name的值是"+filterConfig.getFilterName());
        System.out.println("初始化参数的username的值为"+filterConfig.getInitParameter("username"));
        System.out.println("初始化参数的url的值为"+filterConfig.getInitParameter("url"));
        System.out.println("初始化参数的username的值为"+filterConfig.getServletContext());
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter过滤");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession httpSession = httpServletRequest.getSession();
        Object user = httpSession.getAttribute("user");
        if (user == null) {
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
            return;
        }else {
            //访问权限通过
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("Filter销毁");
        Filter.super.destroy();
    }

    public AdminFilter() {
        System.out.println("Filter构造器");
    }
}
